package com.jinzhi.jzapi.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.itextpdf.text.pdf.PdfReader;
import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.config.IFastConfig;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.utils.DataEnum;
import com.jinzhi.jzweb.domain.ChapterDO;
import com.jinzhi.jzweb.domain.MessageplatfromDO;
import com.jinzhi.jzweb.service.ChapterService;
import com.jinzhi.jzweb.service.MessageplatfromService;
import com.jinzhi.jzweb.utils.PdfUtil;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.oss.service.FileService;
import com.jinzhi.oss.service.OssService;
import com.jinzhi.sms.support.SmsManager;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;


@Slf4j
@RestController
@RequestMapping("/jzApi/utils")
public class ApiUtilsController extends BaseController {
    @Autowired
    private FileService fileService;
    @Autowired
    private DictService dictService;
    @Autowired
    private SmsManager smsSerevice;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private MpConfigService mpConfigService;
    @Autowired
    private MessageplatfromService messageplatfromService;
    @Autowired
    private OssService ossService;
    @Autowired
    private ChapterService chapterService;

    @Autowired
    private SmsManager smsService;

    @Autowired
    private DocumentConverter converter;  //用于转换

    private static final String T_REG_SMS_PREFIX = "TRAINING_REG_";//培训端
    private static final String C_REG_SMS_PREFIX = "CERTIFICATE_REG_";//证书端
    private static final String O_REG_SMS_PREFIX = "ORTHER_REG_";//其他端
    private static BigDecimal bigDecimal;

    static {
        bigDecimal = new BigDecimal(100);
    }

    //授权（必填）
    String grant_type = DataEnum.wx_grant_type.getValue();

    //微信url
    String wx_url = DataEnum.wx_authorization_url.getValue();

    /**
     * api小程序端-文件上传接口
     *
     * @Description: 文件上传，参数：文件
     * @Param: [file]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @PostMapping("/fileImprot")
    @Log("api小程序端-文件上传接口")
    @ApiOperation(value = "api小程序端-文件上传接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> fileImprot(@RequestParam("file") MultipartFile file) {
        String url = "";

        // Random myrd = new Random();

        // Long date = new Date().getTime();

        //  String name = file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf("."));
        // String str2 = file.getOriginalFilename().substring(name.length() + 1, file.getOriginalFilename().length());

        // String fileName = file.getOriginalFilename().replace(file.getOriginalFilename(), date.toString()) + myrd.nextInt(1000) + "." + str2;

        url = ossService.uploadFileOss2(file);

        System.out.println("分片上传视频地址++++++++++++++++++++++++++++++++++++++++++"+url);
        return ApiResult.success("上传成功", url);
    }

    public Map fileToPdf(String fileNameUrl) {
        boolean returnflag = false;
        String uploadPdfUrl = "";
        String imgBaseUrl = "";

        String[] str = fileNameUrl.split("/");
        String newfileName = str[str.length-1];
        //去掉后缀
        String[] str2 = newfileName.split("\\.");
        String newfileName2 = str2[0];
        System.out.println("newfileNameUrl:"+newfileName2);

        /*String filePath = ""; //pdf文件生成保存的路径
        String url1[]=fileNameUrl.split("upload");
        if(url1.length>1){
            filePath = url1[0] + "/upload/pdfFile/";
        }*/

        String savePath = ValuesUtil.localUrl + "/upload/pdfFile/"; //pdf文件生成保存的路径
        //String basePath = "/upload/pdfFile/"; //pdf文件生成保存的路径
        String fileName = newfileName2+"_pdf";
        String fileType = ".pdf"; //pdf文件后缀
        String newFileMix = savePath + fileName + fileType;
        //int pagecount = 0;

        File oldFile = new File(newFileMix);//转换之后文件生成的地址
        if(!oldFile.isFile() && !oldFile.exists()) {

            File downloadFile = null;
            boolean flag = false;
            try {
                // 构造URL
                URL weburl = new URL(fileNameUrl);
                // 打开连接
                URLConnection con = weburl.openConnection();
                // 设置请求超时为5s
                con.setConnectTimeout(5 * 1000);
                // 输入流
                InputStream is = con.getInputStream();
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流
                File sf = new File( ValuesUtil.localUrl + "/upload/pdfFile/");
                if (!sf.exists()) {
                    sf.mkdirs();
                }
                downloadFile = new File(sf.getPath() + "\\" + newfileName);
                System.out.println("downloadFile:" + sf.getPath() + "\\" + newfileName);

                OutputStream os = new FileOutputStream(sf.getPath() + "\\" + newfileName);
                // 开始读取
                while ((len = is.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                // 完毕，关闭所有链接
                os.close();
                is.close();
                flag = true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (flag) {
                //需要转换的文件为 downloadFile
                try {
                    File convertFile = new File(newFileMix);//转换之后文件生成的地址
                    //文件转化
                    converter.convert(downloadFile).to(convertFile).execute();

                    //删除下载的文件
                    if (downloadFile.isFile() && downloadFile.exists()) {
                        downloadFile.delete();
                        System.out.println("删除单个文件" + downloadFile.getName() + "成功！");
                    } else {
                        System.out.println("删除单个文件" + downloadFile.getName() + "失败！");
                    }


                    //上传文件到OSS
                   /* InputStream inputStream = new FileInputStream(convertFile);
                    MultipartFile multipartFile = new MockMultipartFile(convertFile.getName(), inputStream);*/
                    FileInputStream fileInputStream = new FileInputStream(convertFile);
                    MultipartFile multipartFile = new MockMultipartFile(convertFile.getName(), convertFile.getName(),
                            ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

                    uploadPdfUrl= ossService.uploadFileOss(multipartFile);
                    System.out.println("uploadPdfUrl="+uploadPdfUrl);


                    //pdf转换成图片
                    InputStream input = new FileInputStream(new File(newFileMix));

                    byte[] pdfByte = new byte[input.available()];
                    input.read(pdfByte);
                    File sf2 = new File( ValuesUtil.localUrl + "/upload/");
                    if (!sf2.exists()) {
                        sf2.mkdirs();
                    }

                    imgBaseUrl = this.toImageFromBytes( ValuesUtil.localUrl + "/upload/", fileName, pdfByte, "png", 0, -1);
                    if(!imgBaseUrl.equals("")) {
                        returnflag = true;
                        //删除转换之后的文件
                        if (convertFile.isFile() && convertFile.exists()) {
                            convertFile.delete();
                            System.out.println("删除单个文件" + convertFile.getName() + "成功！");
                        } else {
                            System.out.println("删除单个文件" + convertFile.getName() + "失败！");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        Map map = new HashMap();
        map.put("returnflag", returnflag);
        map.put("uploadPdfUrl", uploadPdfUrl);
        map.put("imgBaseUrl", imgBaseUrl);
        map.put("imgName", fileName);

        return map;
    }

    /*
     * PDF转图片
     * @attention: 支持自主选择起始页和结束页
     * @date: 2021-06-8 10:41
     * @param: imgPath
     * 图片全路径
     * @param: imgNamePrefix
     * 图片名称前缀
     * @param: pdfBytes
     * PDF二进制流
     * @param: imgType
     * 图片类型
     * @param: pageStartIndex
     * 开始页：开始转换的页码（第1页，页码为0）
     * @param: pageEndIndex
     * 结束页：结束转换的页码（最后1页，页码为-1）
     * @return: boolean
     * 只有PDF文件所有页数转换成功才返回true
     */
    public String toImageFromBytes(String imgPath, @NotNull String imgNamePrefix, byte[] pdfBytes, String imgType, int pageStartIndex, int pageEndIndex) {
        String baseUrl = "";
        System.out.println("toImageFromBytes:"+imgPath+"  "+imgNamePrefix);
        // 图片名称处理（注意文件名里不要有点，否则一律视为后缀名被抹掉）
        if (imgNamePrefix.indexOf(".") > 0) imgNamePrefix = imgNamePrefix.substring(0, imgNamePrefix.indexOf(".") );

        // 添加路径分隔符
        // if (!imgPath.endsWith("/") && !imgPath.endsWith("\\")) imgPath += File.separator;

        try {
            // 加载PDF
            PDDocument doc = PDDocument.load(pdfBytes);
            PDFRenderer renderer = new PDFRenderer(doc);
            // pdf总页数
            int pageCount = doc.getNumberOfPages();
            System.out.println("该pdf文件共有" + pageCount + "页");
            for (int i = 0; i < pageCount; i++) {
                // dpi越大转换后越清晰，但转换速度越慢
                BufferedImage image = renderer.renderImageWithDPI(i, 250); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                File newImg;

                // 生成图片
                if (pageCount == 1)
                    newImg = new File(imgPath + imgNamePrefix+ "_" + 1 + "." + imgType);
                else
                    newImg = new File(imgPath + imgNamePrefix + "_" + (i + 1) + "." + imgType);

                ImageIO.write(image, imgType, newImg);

                //上传文件到OSS
                FileInputStream fileInputStream = new FileInputStream(newImg);
                MultipartFile multipartFile = new MockMultipartFile(newImg.getName(), newImg.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                String uploadImgUrl= ossService.uploadFileOssNoPrefix(multipartFile);
                System.out.println("uploadImgUrl="+uploadImgUrl);
                System.out.println("pdf第" + (i + 1) + "页转图片成功");


                if(i == 0){
                    String fileName = imgNamePrefix+ "_" + 1 + "." + imgType;
                    baseUrl = uploadImgUrl.substring(0, uploadImgUrl.length() - fileName.length());
                }

                //删除转换之后的文件
                if (newImg.isFile() && newImg.exists()) {
                    newImg.delete();
                    System.out.println("删除单个文件" + newImg.getName() + "成功！");
                } else {
                    System.out.println("删除单个文件" + newImg.getName() + "失败！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("pdf-->;图片失败：" + e.getMessage());
        }

        System.out.println("pdf-->;图片成功");
        System.out.println("图片路径："+baseUrl);
        return baseUrl;
    }

    /**
     * web端-文件上传及将文件转为图片接口
     *
     * @Description: 文件上传，参数：文件
     * @Param: [file]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @PostMapping("/fileImprotAndToImg")
    @Log(" web端-文件上传及将文件转为图片接口")
    @ApiOperation(value = " web端-文件上传及将文件转为图片接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> fileImprotAndToImg(@RequestParam("file") MultipartFile file) {

        boolean returnFlag = false;
        String url = "";
        url = ossService.uploadFileOss(file);

        System.out.println("url:"+url);

        String[] str = url.split("/");
        String newfileName = str[str.length-1];
        //获取后缀
        String[] str2 = newfileName.split("\\.");
        String extension = str2[str2.length-1];
        System.out.println("extension:"+extension);


        Map returnMap = new HashMap();
        if(extension.equals("doc") || extension.equals("docx") || extension.equals("txt") || extension.equals("ppt")
                || extension.equals("pptx") || extension.equals("xls") || extension.equals("xlsx")
        ) {
            returnMap = this.fileToPdf(url);//转换文件为pdf文件
            System.out.println("returnMap:" + returnMap.toString());
            if (returnMap!=null) {
                if(returnMap.get("returnflag")!=null){
                    if((returnMap.get("returnflag")+"").equals("true")){
                        returnFlag =true;
                    }else {
                        returnFlag =false;
                    }
                }else {
                    returnFlag =false;
                }
            }
        }
        if(returnFlag){
            returnMap.put("url", url);
            return ApiResult.success("上传成功", returnMap);
        }else {
            returnMap.put("url", url);
            return ApiResult.fail("上传文件成功，转换文件失败");
        }
    }


    /**
     * api小程序端-文件上传接口
     *
     * @Description: 文件上传，参数：文件
     * @Param: [file]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-09
     */
    @PostMapping("/fileImprot1")
    @Log("api小程序端-文件上传接口")
    @ApiOperation(value = "api小程序端-文件上传接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public Result<String> fileImprot1(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.build(501, "文件为空");
        }
        String url = "";
        //url = fileService.upload(file);
        url = ossService.uploadFileOss(file);
        return Result.ok(url);
    }


    /**
     * api小程序端-关于平台数据接口--公开方法，不需要登录
     *
     * @Description: 关于平台信息查询
     * @Param: []
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selAboutUs")
    @Log("api小程序端-关于平台数据接口")
    @ApiOperation(value = "api小程序端-关于平台数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selAboutUs() {
        Map returnMaps = new HashMap();
        Map<String, String> map = new HashMap<>();
        map.put("name", "关于平台");
        map.put("type", "aboutUs");
        List<Map> maps = dictService.selTypeNameVue(map);
        returnMaps.put("aboutUs", maps);
        return ApiResult.success(returnMaps);
    }

    /**
     * 证书门户端-忘记密码
     *
     * @Description: 证书门户端用户忘记密码操作，更改新密码；参数：手机号码，验证码，新密码
     * @Param: [mobile, code ,newPassWord]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-14
     */
    @GetMapping("/forgetPassWord")
    @Log("证书门户端-忘记密码")
    @ApiOperation(value = "证书门户端-忘记密码", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public Object forgetPassWord(String mobile, String code, String newPassWord) {
        Map map=new HashMap();
        if (StringUtils.isBlank(code)) {
            map.put("msg","验证码为空！");
            return map;
        } else {
            //判断验证码

               boolean b1= smsSerevice.verify1(O_REG_SMS_PREFIX, mobile, code);

               if(!b1){
                   map.put("msg","验证码错误！");
                   return map;
               }

            UserDO userDO = userService.findOneByKv("mobile", mobile);
            if (userDO != null) {
                String salt = UUIDUtils.get();
                String encodePasswd = PasswdUtils.get(newPassWord, salt);
                userDO.setSalt(salt);
                userDO.setPassword(encodePasswd);

//                List<Long> list = new ArrayList<>();
//                list.add(56L);
//                userDO.setroleIds(list);
                boolean b = userService.updateById(userDO);
                if (b) {
                    map.put("msg","修改成功！");
                    return map;
                }
            } else {
                map.put("msg","修改失败！");
                return map;
            }
        }
        map.put("msg","修改失败，请联系管理员！");
        return map;
    }

    @PostMapping("/sendPassWordCode")
    @Log("发送修改密码验证短信")
    @ApiOperation(value = "发送修改密码验证短信", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ApiResult<?> sendPassWordCode(String wxId, String mobile) {
        //第一步验证手机号格式
        if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }
        UserDO   users = userService.findOneByKv("mobile",mobile);

        if(users==null){
            //return Result.build(500, "用户不存在，请联系相关负责人！");
            return ApiResult.fail("用户不存在，请联系相关负责人进行注册或绑定！");
        }

        //第二步发送短信，错误信息由方法直接返回
        Object smsDemo = EhCacheUtil.get("修改密码验证");
        if(smsDemo == null){
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("修改密码验证");
            if(messageplatfromDO != null){
                EhCacheUtil.put("修改密码验证",messageplatfromDO.getSmsDemo());
                if (wxId.equals("101")) {
                    smsSerevice.sendPassword(C_REG_SMS_PREFIX, mobile,messageplatfromDO.getSmsDemo());
                } else if (wxId.equals("102")) {
                    smsSerevice.sendPassword(T_REG_SMS_PREFIX, mobile,messageplatfromDO.getSmsDemo());
                } else {
                    smsSerevice.sendPassword(O_REG_SMS_PREFIX, mobile,messageplatfromDO.getSmsDemo());
                }
            }else{
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        }else{
            if (wxId.equals("101")) {
                smsSerevice.sendPassword(C_REG_SMS_PREFIX, mobile,(String) smsDemo);
            } else if (wxId.equals("102")) {
                smsSerevice.sendPassword(T_REG_SMS_PREFIX, mobile,(String) smsDemo);
            } else {
                smsSerevice.sendPassword(O_REG_SMS_PREFIX, mobile,(String) smsDemo);
            }
        }

        return ApiResult.success("发送成功");
    }









    @GetMapping("/sendLoginCode")
    @ResponseBody
    public ApiResult<?> sendLoginCode(String name) {

        String mobile = null;
        if (!StringUtils.isBlank(name)){
            EntityWrapper<UserDO> entityWrapper =new EntityWrapper();
            entityWrapper.eq("name",name);
            UserDO userDO = userService.selectOne(entityWrapper);
            mobile = userDO.getMobile(); //根据用户名获取手机号
        }

        //第一步验证手机号格式
        if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }

        //第二步发送短信，错误信息由方法直接返回
        Object smsDemo = EhCacheUtil.get("后台登录验证码");
        if (smsDemo == null) {
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("注册短信验证");
            if (messageplatfromDO != null) {
                EhCacheUtil.put("后台登录验证码", messageplatfromDO.getSmsDemo());
                smsService.sendreg(O_REG_SMS_PREFIX, mobile, messageplatfromDO.getSmsDemo());
            } else {
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        } else {
            smsService.sendreg(O_REG_SMS_PREFIX, mobile, (String) smsDemo);
        }

        return ApiResult.success("发送成功");
    }





    @GetMapping("/sendQrCode")
    @ResponseBody
    public ApiResult<?> sendQrCode(String phone) {
        //第一步验证手机号格式
        if (StringUtils.isBlank(phone)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(phone)) {
            return ApiResult.format("mobile");
        }
        //第二步发送短信，错误信息由方法直接返回
        Object smsDemo = EhCacheUtil.get("拖育园参观二维码");
        if (smsDemo == null) {
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("注册短信验证");
            if (messageplatfromDO != null) {
                EhCacheUtil.put("拖育园参观二维码", messageplatfromDO.getSmsDemo());
                smsService.sendreg(O_REG_SMS_PREFIX, phone, messageplatfromDO.getSmsDemo());
            } else {
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        } else {
            smsService.sendreg(O_REG_SMS_PREFIX, phone, (String) smsDemo);
        }

        return ApiResult.success("发送成功");
    }






    @Log("选择课程对应章节")
    @ResponseBody
    @GetMapping("/byCourToChapList")
    @ApiOperation(value = "选择课程对应章节", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Result<?> distributionSecond(String coursesId) {
        if (StringUtils.isNotBlank(coursesId)) {
            List<Map<Object, Object>> mapsre = new ArrayList<>();
            //只查询最上级的知识点
            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", Long.parseLong(coursesId), "state", 0);
            if (chapterDOS != null && chapterDOS.size() > 0) {
                for (ChapterDO chapterDO : chapterDOS) {
                    Map map = new HashMap();
                    map.put("id", chapterDO.getId());
                    map.put("name", chapterDO.getName());
                    mapsre.add(map);
                }
            }

            return Result.ok(mapsre);

        }
        return Result.fail("请先选择课程！");
    }

    @PostMapping("/savaOpenId")
    @Log("api小程序端-保存openId")
    @ApiOperation(value = "api小程序端-保存openId", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> savaOpenId(@RequestHeader(value = TOKEN_TAG, required = false) String token,Integer wxId,String code) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        //登录凭证不能为空
        if (StringUtils.isBlank(code)) {
            return ApiResult.lack("code");
        }
        MpConfigDO mpConfigDO = mpConfigService.selectById(wxId);
        if (null == mpConfigDO) {
            throw new IFastApiException(ApiEnumError.getConfFail.getCodeStr());
        }
        //请求参数
        String params = "appid=" + mpConfigDO.getAppId() + "&secret=" + mpConfigDO.getAppSecret() + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet(wx_url, params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        String errcode = null;
        if (null != json.get("errcode")) {
            errcode = json.get("errcode").toString();
        }
        if (StringUtils.isNotBlank(errcode)) {
            String errmsg = json.getString("errmsg");
            return ApiResult.build(ApiEnumError.wxThrowFail.getCode(), "微信错误码：" + errcode + "\n" + "微信错误信息：" + errmsg);
        }

        //用户的唯一标识（openid）
        String openid = json.getString("openid");
        if (wxId.equals(101)) {
            user.setCerOpenId(openid);//证书小程序openId
        } else if (wxId.equals(102)) {
            user.setTraOpenId(openid);//培训小程序openId
        }
        List<Long> roleIds = new ArrayList<>();
        //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
        List<UserRoleDO> userRoleDO = userRoleService.findByKv("userId", user.getId());
        if (userRoleDO != null && userRoleDO.size() > 0) {
            for (int i = 0; i < userRoleDO.size(); i++) {
                roleIds.add(userRoleDO.get(i).getRoleId());
            }
        } else {
            roleIds.add(56L);
        }
        user.setroleIds(roleIds);
        boolean b = userService.updateById(user);
        if(b){
            return ApiResult.success();
        }else{
            return ApiResult.fail();
        }
    }

}
